package com.thlws.redis.transaction;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * @author HanleyTang
 * @date 2018-12-15
 */
public class JedisTransaction {


    /*****
     * 事务开启步骤
     * 1.jedis.watch("key1","key2","key3") //开始检视
     * 2 Transaction transaction = jedis.multi();  //获取事务对象
     *      transaction.set(key,value)  //执行事务代码
     * 3 List<Object> r =  transaction2.exec();  //提交事务
     *  通过判断r是否为空，判断事务是否成功
     * 4 jedis.unwatch(); //解除检视
     */

    public static void main(String[] args) {

        try(Jedis jedis = new Jedis("localhost",6379);){

            jedis.flushDB();

            //获取事务对象
            Transaction transaction = jedis.multi();

            jedis.set("key1", "jack");
            //模拟异常
            int r = 9/0;
            jedis.set("key2", "hanley");

            //未提交前,db不会有数据
            transaction.exec();


            //======事务标准流程==================
            jedis.set("money", "30");
            jedis.watch("money");
            //开始watch后，在事务提交前，被watch的数据被本事务以为的操作修改，则事务不会提交
            jedis.set("money", "90");

            Transaction transaction2 = jedis.multi();
            transaction2.set("money", "99");//watch后，只能是事务对象修改
            List<Object> r2 =  transaction2.exec();
            jedis.unwatch();




        }
    }
}
